package com.cssy.yd.logic.web;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.service.IScAuthorityStatusService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicMeasurementUnitService;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoItemDO;
import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.cssy.yd.logic.entity.LogicPoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicPoWareItemDO;
import com.cssy.yd.logic.entity.LogicSoWareItemDO;
import com.cssy.yd.logic.service.ILogicPoItemService;
import com.cssy.yd.logic.service.ILogicPoService;
import com.cssy.yd.logic.service.ILogicPoWareItemBatchService;
import com.cssy.yd.logic.service.ILogicPoWareService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

@Controller
@RequestMapping("/yd/logic/poware")
public class PoWareController extends BaseController<LogicPoWareDO> {
	private static final String MANAGER = "/yd/logic/poware/PoWareManager";// 列表页面
	private static final String EIDT = "/yd/logic/poware/PoWareOperation";// 添加、修改、显示页面
	private static final String ITEMMANAGER = "/yd/logic/poware/PoWareItemManager";// 列表页面
	
	@Resource(name = "logicPoService")
	private ILogicPoService logicPoService;
	@Resource(name = "logicPoItemService")
	private ILogicPoItemService logicPoItemService;
	
	@Resource(name = "logicPoWareService")
	private ILogicPoWareService logicPoWareService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name="basicMeasurementUnitService")
	private IBasicMeasurementUnitService basicMeasurementUnitService;

	@Resource(name="logicPoWareItemBatchService")
	private ILogicPoWareItemBatchService logicPoWareItemBatchService;
	
	@Resource(name="scAuthorityStatusService")
	private IScAuthorityStatusService scAuthorityStatusService;
	
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}
	@RequestMapping("/itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		LogicPoWareItemDO poWareItem=JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicPoWareItemDO.class);
		LogicPoWareItemBatchDO poWareItemBatchDO = new LogicPoWareItemBatchDO();
		poWareItemBatchDO.setMaterialsid(poWareItem.getMaterialsid());
		poWareItemBatchDO.setWareitemid(poWareItem.getId());
		poWareItemBatchDO.setCode(poWareItem.getCode());
		poWareItemBatchDO.setName(poWareItem.getName());
		poWareItemBatchDO.setSpec(poWareItem.getSpec());
		poWareItemBatchDO.setJunit(poWareItem.getJunit());
		poWareItemBatchDO.setHealthycount(poWareItem.getHealthycount());
		poWareItemBatchDO.setUnit(poWareItem.getUnit());
		poWareItemBatchDO.setBatch(poWareItem.getBatch());
		poWareItemBatchDO.setBadcount(poWareItem.getBadcount());
		poWareItemBatchDO.setInCount(poWareItem.getInCount());
		poWareItemBatchDO.setJquantity(poWareItem.getJquantity());
		poWareItemBatchDO.setQuantity(poWareItem.getQuantity());
		poWareItemBatchDO.setState(poWareItem.getState());
		poWareItemBatchDO.setUnitconvert(poWareItem.getUnitconvert());
		if(poWareItem.getItemBatchDO() != null & !"".equals(poWareItem.getItemBatchDO())){
			request.setAttribute("itemBatchDOs", poWareItem.getItemBatchDO());
		}
//		if(poWareItem.getDelItemBatchDO() != null & !"".equals(poWareItem.getDelItemBatchDO())){
//			request.setAttribute("delItemBatchDOs", poWareItem.getDelItemBatchDO());
//		}
		
		request.setAttribute("billstatus", billstatus);
		request.setAttribute("poWareItemBatch", JSONArray.toJSONString(poWareItemBatchDO));
		return ITEMMANAGER;
	}
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//String username =request.getParameter("username");
//		String username =SessionUtil.getUser(request).getName();
//		 List<String> list =new AuthorityUtil().getStatus(request,scAuthorityStatusService);
//		 String authorityName="";
//		 for (int i = 0; i < list.size(); i++) {
//			 if(i!=(list.size()-1)){
//				 authorityName +="'"+list.get(i)+"',";
//			 }else{
//				 authorityName +="'"+list.get(i)+"'";
//			 }
//		}
//		String str = "(dcruser='"+username+"' or (dcruser<>'"+username+"' and  billstatus in(select status from sc_authority_status where authorityName in("+authorityName+"))))";
		 JqGridHandler hander=new JqGridHandler(request);
		 SearchConditions scs = new SearchConditions();
		 hander.getWheres(scs);
		 Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,"whcode");
		 scs.addCondition((String)sqlMap.get("option"), (List)sqlMap.get("roleWhList"));
		 //scs.addCondition("billtype","1",SearchCondition.OP_EQUAL);
		 scs.setOrderBy("dctime desc");
//		 if(!"".equals(username) && username != null){
//			 scs.addCondition("authorityStatus",str,"");
//		 }
		 SearchResult result= logicPoWareService.findListByExample(scs);
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);

	}	
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		List<LogicPoWareItemBatchDO> itemBatchDOs=null;
		if(itembatch != null  && !"".equals(itembatch)){
			itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicPoWareItemBatchDO.class);
		}
		SearchResult result= new SearchResult();
//		String wareitemid =request.getParameter("wareitemid");
//		String code =request.getParameter("code");
//		JqGridHandler hander=new JqGridHandler(request);
//		 SearchConditions scs = new SearchConditions();
//		 hander.getWheres(scs);
//		 scs.setRemovedProperty(null);
//		 List<LogicPoWareItemBatchDO>list= new ArrayList<LogicPoWareItemBatchDO>();
//		 if((!"".equals(wareitemid) && wareitemid != null) && (!"".equals(code) && code != null)){
//			 scs.addCondition("wareItemId", wareitemid, SearchCondition.OP_EQUAL);
//			 scs.addCondition("code", code, SearchCondition.OP_EQUAL);
//			 list= logicPoWareItemBatchService.findListByExample(scs).getResults();
//		 }
//		 if(itemBatchDOs != null){
//			 for (LogicPoWareItemBatchDO logicPoWareItemBatchDO : itemBatchDOs) {
//					if(logicPoWareItemBatchDO.getId() == null){
//						list.add(logicPoWareItemBatchDO);
//					}
//				}
//		 }
		if(itemBatchDOs != null && itemBatchDOs.size() > 0){
			result.setRecordCount(itemBatchDOs.size());
			result.setResults(itemBatchDOs);
		}
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
		
	}
	@RequestMapping(value = "/poitemlist")
	public void poitemlist(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String poId = request.getParameter("poid");
		SearchConditions scs = new SearchConditions();
		if(poId!=null&&!"".equals(poId)){
			scs.addCondition("po_id", poId, SearchCondition.OP_EQUAL);
		}else{
			scs.addCondition("po_id", " ", SearchCondition.OP_EQUAL);
		}
		//scs.addCondition("jquantity", "in_count", SearchCondition.OP_NOTEQUAL);
		scs.setRemovedProperty(null);
		scs.setOrderBy("code asc");
		SearchResult sr = logicPoItemService.findListByExample(scs);
		List<LogicPoItemDO> lItemDOs = sr.getResults();
		List<LogicPoWareItemDO> listpwItemDOs = new ArrayList<LogicPoWareItemDO>();
		LogicPoWareItemDO poWareItemDO = null ;
		for (LogicPoItemDO logicPoItemDO : lItemDOs) {
			poWareItemDO = new LogicPoWareItemDO();
			if(Double.parseDouble(((logicPoItemDO.getJquantity()==null?0.0:logicPoItemDO.getJquantity())+""))>Double.parseDouble((logicPoItemDO.getInCount()==null?0.0:logicPoItemDO.getInCount())+"")){
				poWareItemDO.setMaterialsid(logicPoItemDO.getMaterialsid());
				poWareItemDO.setName(logicPoItemDO.getName());
				poWareItemDO.setCode(logicPoItemDO.getCode());
				poWareItemDO.setSpec(logicPoItemDO.getSpec());
				poWareItemDO.setPrice(logicPoItemDO.getHsdiscountMoney());
				poWareItemDO.setJunit(logicPoItemDO.getJunit());
				poWareItemDO.setUnit(logicPoItemDO.getUnit());
				poWareItemDO.setHealthycount(logicPoItemDO.getJquantity());
				poWareItemDO.setBadcount(logicPoItemDO.getQuantity());
				poWareItemDO.setInCount(logicPoItemDO.getInCount());
				poWareItemDO.setUnitconvert(logicPoItemDO.getUnitconvert());
				poWareItemDO.setOpenBatch(logicPoItemDO.getOpenBatch());
				listpwItemDOs.add(poWareItemDO);
			}
			
		}
		SearchResult result =new SearchResult();
		result.setResults(listpwItemDOs);
		result.setRecordCount(listpwItemDOs.size());
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("polist", findpolist());
		if (OperationFlag.ADD.equals(flag)) {// 我新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicPoWareDO lpd = logicPoWareService.findListById(id);
			/*SearchConditions scs = new SearchConditions();
			scs.setRemovedProperty(null);
			scs.addCondition("powareid", lpd.getId(), SearchCondition.OP_EQUAL);
			scs.setOrderBy("code asc");
			List<LogicPoWareItemDO> lp = logicPoWareService.findItemListByExample(scs).getResults();*/
			model.addAttribute("poware", lpd);
			//model.addAttribute("wareitem", lp);
		}
		return EIDT;
	}
	

	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicPoWareDO lpd = logicPoWareService.findListById(id);
			SearchConditions scs = new SearchConditions();
			scs.setRemovedProperty(null);
			scs.addCondition("powareid", lpd.getId(), SearchCondition.OP_EQUAL);
			scs.setOrderBy("code asc");
			List<LogicPoWareItemDO> lp = logicPoWareService.findItemListByExample(scs).getResults();
			OutJsonGrid out = new OutJsonGrid(lp);
			out.printJSon(response);
		}
	}
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPoWareDO curAP, BindingResult result, Model model) throws SyBaseException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata = request.getParameter("itemdata");
		//String type=request.getParameter("type");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料不能为空！");
			return bodyMap.modelMap;
		}else{
//			if("0".equals(type)){
				List<LogicPoWareItemDO> poWareItem  = JSONArray.parseArray(itemdata, LogicPoWareItemDO.class);
				for (LogicPoWareItemDO logicPoWareItemDO : poWareItem) {
					if("Y".equals(logicPoWareItemDO.getOpenBatch())){
						if("".equals(logicPoWareItemDO.getItemBatchDO()) || logicPoWareItemDO.getItemBatchDO()==null){
							bodyMap.isFail();
							bodyMap.configWebInfor("物料编码为:'"+logicPoWareItemDO.getCode()+"'没有分批次填写数据！");
							return bodyMap.modelMap;
						}else{
							List<LogicPoWareItemBatchDO> batchDOs  = JSONArray.parseArray(logicPoWareItemDO.getItemBatchDO(), LogicPoWareItemBatchDO.class);
							if(batchDOs==null || batchDOs.size() <= 0){
								bodyMap.isFail();
								bodyMap.configWebInfor("物料编码为:'"+logicPoWareItemDO.getCode()+"'没有分批次填写数据！");
								return bodyMap.modelMap;
							}
						}
					}
				}
//			}
			
		}
		
		if(!"".equals(curAP.getPocode()) && curAP.getPocode() != null){
			SearchConditions sc = new SearchConditions();
			sc.addCondition("pocode", curAP.getPocode());
			List<LogicPoDO> polist =  logicPoService.findListByExample(sc).getResults();
			if(Integer.parseInt(polist.get(0).getBillstatus())>=5){
				bodyMap.isFail();
				bodyMap.configWebInfor("该采购订单已经完结!");
				return bodyMap.modelMap;
			}
		}
		
		Map<String, Object> map  = new HashMap<String, Object>();
		if(curAP.getPocode() != null && !"".equals(curAP.getPocode())){
			map.put("pocode", curAP.getPocode());
		}
		if(curAP.getPowarecode() != null && !"".equals(curAP.getPowarecode())){
			map.put("powarecode", curAP.getPowarecode());
		}
		int count= logicPoWareService.untreatedPowarecode(map);
		if(count > 0 ){
			bodyMap.isFail();
			bodyMap.configWebInfor("该采购订单有对应的入库单未处理,请先处理!");
			return bodyMap.modelMap;
		}
		
		try {
			/*if(!StringUtil.valitate(curAP.getBatch())&&!StringUtil.valitate(curAP.getId())){
				bodyMap.isFail();
				bodyMap.configWebInfor("入库的批次不能为空！");
				return bodyMap.modelMap;
			}else{
				if(null==curAP.getBillstatus() || curAP.getBillstatus()<3){
					SearchConditions scs = new SearchConditions();
					if(StringUtil.valitate(curAP.getId())){
						 scs.addCondition("id",curAP.getId(),SearchCondition.OP_NOTEQUAL);
					 }
					 scs.addCondition("batch",curAP.getBatch(),SearchCondition.OP_EQUAL);
					 SearchResult sr= logicPoWareService.findListByExample(scs);
					 if(sr.getResults().size()>0){
							bodyMap.isFail();
							bodyMap.configWebInfor("您填写的批次号已存在请重新填写");
							return bodyMap.modelMap;
					}
				}
			}*/
			logicPoWareService.waresave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;

	}
	

	
	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicPoWareDO ld=logicPoWareService.findListById(field);
				if(ld!=null){
					ld.setRemoved(1);
					logicPoWareService.update(ld, SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 获取未入库和部分入库的采购单号
	 * @return
	 */
	private List<LogicPoDO> findpolist(){
		SearchConditions scs = new SearchConditions();
		 List<String> strlist=new ArrayList<String>();
		 strlist.add("3");
		 strlist.add("4");
//		 strlist.add("8");
		 scs.addCondition("billstatus",strlist);
		 scs.setOrderBy("dctime desc");
		 SearchResult result= logicPoService.findListByExample(scs);
		return result.getResults();
	}
//	
//	@RequestMapping(value = "/exportExcel")
//	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
//
//		try {
//			
//			
//			String id = request.getParameter("id");
//			LogicPoWareDO poware=new LogicPoWareDO();
//			List<LogicPoWareItemDO> lp=new ArrayList<LogicPoWareItemDO>();
//			List<LogicFreightageDO> freightageDOs=new ArrayList<LogicFreightageDO>();
//			if(!"".equals(id)&&id!=null){
//				poware = logicPoWareService.findListById(id);
//			}
//			if(poware.getId()!=null){
//				SearchConditions scs = new SearchConditions();
//				scs.setRemovedProperty(null);//判断是否有删除标识
//				scs.addCondition("powareid", poware.getId(), SearchCondition.OP_EQUAL);
//				lp = logicPoWareService.findItemListByExample(scs).getResults();
//				SearchConditions sc = new SearchConditions();
//				sc.setRemovedProperty(null);//判断是否有删除标识
//				sc.addCondition("tid", poware.getId(), SearchCondition.OP_EQUAL);
//				freightageDOs=logicFreightageService.findListByExample(sc).getResults();
//			}
//			if(lp.size()>0){
//				request.setAttribute("poware", poware);
//				request.setAttribute("lp", lp);
//				request.setAttribute("row", lp.size());
//				if(freightageDOs.size()>0){
//					for(int i=0;i<freightageDOs.size();i++){
//						if("铁运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("T", freightageDOs.get(i).getFreightageprice());
//						}
//						if("海运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("H", freightageDOs.get(i).getFreightageprice());
//						}
//						if("短运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("D", freightageDOs.get(i).getFreightageprice());
//						}
//						if("装卸费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Z", freightageDOs.get(i).getFreightageprice());
//						}
//						if("落箱费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("L", freightageDOs.get(i).getFreightageprice());
//						}
//						if("其他".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Q", freightageDOs.get(i).getFreightageprice());
//						}
//					}
//					
//				}
//				
//				response.setContentType("application/vnd.ms-excel");
//				response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
//			
//				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/PoWarePrint.jsp");
//			
//				dispatcher.forward(request, response);
//			}
//		} catch (ServletException e) {
//			e.printStackTrace();
//		}
//	}
//	@RequestMapping(value = "/exportExcel")
//	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
//		
//		String id = request.getParameter("id");
//		LogicPoWareDO pw=new LogicPoWareDO();
//		List<LogicPoWareItemDO> itemlist=new ArrayList<LogicPoWareItemDO>();
//		if(!"".equals(id)&&id!=null){
//			pw =logicPoWareService.findListById(id);
//		}
//		if(pw.getId()!=null){
//			SearchConditions scs = new SearchConditions();
//			scs.addCondition("powareid", pw.getId(),SearchCondition.OP_EQUAL);
//			scs.setLimitPage(false);
//			scs.setRemovedProperty(null);
//			scs.setOrderBy("code asc");
//			itemlist =logicPoWareService.findItemListByExample(scs).getResults();
//		}
//		HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象  
//		HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet对象  
//		sheet.setDefaultRowHeight((short)158);
//		if(itemlist.size()>0){
//			HSSFCellStyle style = wb.createCellStyle();      
//			style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框       
//			style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框       
//			style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框       
//			style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
//			style.setBorderBottom((short) 1);
//			style.setBorderLeft((short) 1);
//			style.setBorderRight((short) 1);
//			style.setBorderTop((short) 1);
//			HSSFFont font = wb.createFont();
//			font.setFontName("宋体");
//			font.setFontHeightInPoints((short) 10);
//			style.setFont(font);
//			style.setAlignment((short) 2);
//			style.setVerticalAlignment((short) 1l);
//			
//			HSSFCellStyle style1 = wb.createCellStyle();
//			style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 指定单元格居中对齐 
//			style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐
//			HSSFFont font1 = wb.createFont();
//			font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//			font1.setFontHeightInPoints((short) 14);
//			font1.setFontName("宋体");
//			style1.setFont(font1);
//			
//
//			HSSFCellStyle style2 = wb.createCellStyle();
//			style2.setFont(font);
//			style2.setWrapText(false);  
//			
//			HSSFCellStyle style3 = wb.createCellStyle();   
//			style3.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框       
//			style3.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框       
//			style3.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框       
//			style3.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
//			style3.setBorderBottom((short) 1);
//			style3.setBorderLeft((short) 1);
//			style3.setBorderRight((short) 1);
//			style3.setBorderTop((short) 1);
//			style3.setFont(font);
//			
//			HSSFRow row1 = sheet.createRow((short)0);//建立新行
//			Region region = new Region(0,(short) 0, 0, (short) 10);//指定合并区域
//			sheet.addMergedRegion(region);
//			HSSFCell cell1 = row1.createCell((short)0);
//			cell1.setCellValue("吉林华微斯帕克电气有限公司");
//			cell1.setCellStyle(style1);
//			
//			HSSFRow row2 = sheet.createRow((short)1);//建立新行
//			Region region1 = new Region(1,(short) 0, 1, (short) 10);//指定合并区域
//			sheet.addMergedRegion(region1);
//			HSSFCell cell2 = row2.createCell((short)0);
//			cell2.setCellValue("验收入库单");
//			cell2.setCellStyle(style1);
//			
//			HSSFRow row3 = sheet.createRow((short)2);//建立新行
//			HSSFCell c11 = row3.createCell((short)0);
//			c11.setCellStyle(style2);
//			HSSFCell c12 = row3.createCell((short)1);
//			c12.setCellValue("入库仓库：");
//			c12.setCellStyle(style2);
//			HSSFCell c13 = row3.createCell((short)2);
//			c13.setCellValue(pw.getWhname());
//			c13.setCellStyle(style2);
//			HSSFCell c14 = row3.createCell((short)3);
//			c14.setCellStyle(style2);
//			HSSFCell c15 = row3.createCell((short)4);
//			c15.setCellStyle(style2);
//			HSSFCell c16 = row3.createCell((short)5);
//			c16.setCellStyle(style2);
//			HSSFCell c17 = row3.createCell((short)6);
//			c17.setCellStyle(style2);
//			HSSFCell c18 = row3.createCell((short)7);
//			c18.setCellValue("表单编号：");
//			c18.setCellStyle(style2);
//			HSSFCell c19 = row3.createCell((short)8);
//			c19.setCellStyle(style2);
//			HSSFCell c20 = row3.createCell((short)9);
//			c20.setCellStyle(style2);
//			HSSFCell c21 = row3.createCell((short)10);
//			c21.setCellStyle(style2);
//			
//			HSSFRow row4 = sheet.createRow((short)3);//建立新行
//			HSSFCell c22 = row4.createCell((short)0);
//			c22.setCellStyle(style2);
//			HSSFCell c23 = row4.createCell((short)1);
//			c23.setCellValue("验收入库单号：");
//			c23.setCellStyle(style2);
//			HSSFCell c24 = row4.createCell((short)2);
//			c24.setCellValue(pw.getPowarecode());
//			c24.setCellStyle(style2);
//			HSSFCell c25 = row4.createCell((short)3);
//			c25.setCellValue("请购部门：");
//			c25.setCellStyle(style2);
//			HSSFCell c26 = row4.createCell((short)4);
//			c26.setCellStyle(style2);
//			HSSFCell c27 = row4.createCell((short)5);
//			c27.setCellStyle(style2);
//			HSSFCell c28 = row4.createCell((short)6);
//			c28.setCellValue("收料日期：");
//			c28.setCellStyle(style2);
//			HSSFCell c29 = row4.createCell((short)7);
//			c29.setCellValue(DateUtils.dateToString(pw.getRkdate(),"yyyy-MM-dd"));
//			c29.setCellStyle(style2);
//			HSSFCell c30 = row4.createCell((short)8);
//			c30.setCellStyle(style2);
//			HSSFCell c31 = row4.createCell((short)9);
//			c31.setCellValue("制单人：");
//			c31.setCellStyle(style2);
//			HSSFCell c32 = row4.createCell((short)10);
//			c32.setCellValue(pw.getCreatename());
//			c32.setCellStyle(style2);
//			
//			HSSFRow row5 = sheet.createRow((short)4);//建立新行
//			HSSFCell c33 = row5.createCell((short)0);
//			c33.setCellStyle(style2);
//			HSSFCell c34 = row5.createCell((short)1);
//			c34.setCellValue("采购订单编号：");
//			c34.setCellStyle(style2);
//			HSSFCell c35 = row5.createCell((short)2);
//			c35.setCellValue(pw.getPocode());
//			c35.setCellStyle(style2);
//			HSSFCell c36 = row5.createCell((short)3);
//			c36.setCellValue("供应厂商：");
//			c36.setCellStyle(style2);
//			HSSFCell c37 = row5.createCell((short)4);
//			c37.setCellValue(pw.getSpname());
//			c37.setCellStyle(style2);
//			HSSFCell c38 = row5.createCell((short)5);
//			c38.setCellStyle(style2);
//			HSSFCell c39 = row5.createCell((short)6);
//			c39.setCellValue("备注：");
//			c39.setCellStyle(style2);
//			HSSFCell c40 = row5.createCell((short)7);
//			c40.setCellValue(pw.getRemark());
//			c40.setCellStyle(style2);
//			HSSFCell c41 = row5.createCell((short)8);
//			c41.setCellStyle(style2);
//			HSSFCell c42 = row5.createCell((short)9);
//			c42.setCellValue("验收人：");
//			c42.setCellStyle(style2);
//			HSSFCell c43 = row5.createCell((short)10);
//			c43.setCellValue(pw.getYsr());
//			c43.setCellStyle(style2);
//			
//			HSSFRow row6 = sheet.createRow((short)5);//建立新行
//			Region region2 = new Region(5,(short) 0, 6, (short)0);
//			Region region3 = new Region(5,(short) 1, 6, (short)1);
//			Region region4 = new Region(5,(short) 2, 6, (short)2);
//			Region region5 = new Region(5,(short) 3, 6, (short)3);
//			Region region6 = new Region(5,(short) 4, 6, (short)4);
//			Region region7 = new Region(5,(short) 5, 6, (short)5);
//			Region region8 = new Region(5,(short) 6, 6, (short)6);
//			Region region9 = new Region(5,(short) 9, 6, (short)9);
//			Region region10 = new Region(5,(short) 10, 6, (short)10);
//			Region region11 = new Region(5,(short) 7, 5, (short)8);
//			sheet.addMergedRegion(region2);			
//			sheet.addMergedRegion(region3);			
//			sheet.addMergedRegion(region4);			
//			sheet.addMergedRegion(region5);			
//			sheet.addMergedRegion(region6);			
//			sheet.addMergedRegion(region7);			
//			sheet.addMergedRegion(region8);			
//			sheet.addMergedRegion(region9);			
//			sheet.addMergedRegion(region10);			
//			sheet.addMergedRegion(region11);	
//			
//			HSSFCell cell3 = row6.createCell((short)0);
//			cell3.setCellValue("序号");
//			cell3.setCellStyle(style);		
//			HSSFCell cell4 = row6.createCell((short)1);
//			cell4.setCellValue("物料编码");
//			cell4.setCellStyle(style);		
//			HSSFCell cell5 = row6.createCell((short)2);
//			cell5.setCellValue("描述");
//			cell5.setCellStyle(style);		
//			HSSFCell cell6 = row6.createCell((short)3);
//			cell6.setCellValue("批次");
//			cell6.setCellStyle(style);		
//			HSSFCell cell7 = row6.createCell((short)4);
//			cell7.setCellValue("单位");
//			cell7.setCellStyle(style);		
//			HSSFCell cell8 = row6.createCell((short)5);
//			cell8.setCellValue("收料数量");
//			cell8.setCellStyle(style);		
//			HSSFCell cell9 = row6.createCell((short)6);
//			cell9.setCellValue("抽样数量");
//			cell9.setCellStyle(style);		
//			HSSFCell cell10 = row6.createCell((short)7);
//			cell10.setCellValue("NG");
//			cell10.setCellStyle(style);	
//			row6.createCell((short) 8).setCellStyle(style);		
//			HSSFCell cell11 = row6.createCell((short)9);
//			cell11.setCellValue("判定");
//			cell11.setCellStyle(style);	
//			HSSFCell cell12 = row6.createCell((short)10);
//			cell12.setCellValue("入库数量");
//			cell12.setCellStyle(style);
//			
//			HSSFRow row7 = sheet.createRow((short)6);//建立新行
//			row7.createCell((short) 0).setCellStyle(style);	
//			row7.createCell((short) 1).setCellStyle(style);	
//			row7.createCell((short) 2).setCellStyle(style);	
//			row7.createCell((short) 3).setCellStyle(style);	
//			row7.createCell((short) 4).setCellStyle(style);	
//			row7.createCell((short) 5).setCellStyle(style);	
//			row7.createCell((short) 6).setCellStyle(style);	
//			HSSFCell cell20 = row7.createCell((short)7);
//			cell20.setCellValue("数量");
//			cell20.setCellStyle(style);		
//			HSSFCell cell21 = row7.createCell((short)8);
//			cell21.setCellValue("原因");
//			cell21.setCellStyle(style);		
//			row7.createCell((short) 9).setCellStyle(style);	
//			row7.createCell((short) 10).setCellStyle(style);	
//			
//			for(int i=0;i<itemlist.size();i++){
//				HSSFRow row8 = sheet.createRow((short)(7+i));//建立新行
//				
//				sheet.setColumnWidth(0, 1500);
//				HSSFCell cell24 = row8.createCell((short)0);
//				cell24.setCellStyle(style);
//				cell24.setCellValue(i+1);
//				
//				sheet.setColumnWidth(1, 4500);
//				HSSFCell cell25 = row8.createCell((short)1);
//				cell25.setCellStyle(style);
//				cell25.setCellValue(itemlist.get(i).getCode());
//				
//				sheet.setColumnWidth(2, 8000);
//				HSSFCell cell26 = row8.createCell((short)2);
//				cell26.setCellStyle(style);
//				cell26.setCellValue(itemlist.get(i).getName()+";"+itemlist.get(i).getSpec());
//				
//				sheet.setColumnWidth(3, 3500);
//				HSSFCell cell27 = row8.createCell((short)3);
//				cell27.setCellStyle(style);
//				cell27.setCellValue(itemlist.get(i).getBatch());
//
//				sheet.setColumnWidth(4, 1600);
//				HSSFCell cell28 = row8.createCell((short)4);
//				cell28.setCellStyle(style);
//				cell28.setCellValue(itemlist.get(i).getJunit());
//				
//				sheet.setColumnWidth(5, 2500);
//				HSSFCell cell29 = row8.createCell((short)5);
//				cell29.setCellStyle(style);
//				cell29.setCellValue("");
//				
//				sheet.setColumnWidth(6, 2500);
//				HSSFCell cell30 = row8.createCell((short)6);
//				cell30.setCellStyle(style);
//				cell30.setCellValue("");
//				
//				sheet.setColumnWidth(7, 2500);
//				HSSFCell cell31 = row8.createCell((short)7);
//				cell31.setCellStyle(style);
//				cell31.setCellValue("");
//				
//				sheet.setColumnWidth(8, 4500);
//				HSSFCell cell32 = row8.createCell((short)8);
//				cell32.setCellStyle(style);
//				cell32.setCellValue("");
//				
//				sheet.setColumnWidth(9, 2500);
//				HSSFCell cell33 = row8.createCell((short)9);
//				cell33.setCellStyle(style);
//				cell33.setCellValue("");
//				
//				sheet.setColumnWidth(10, 2500);
//				HSSFCell cell34 = row8.createCell((short)10);
//				cell34.setCellStyle(style);
//				cell34.setCellValue(itemlist.get(i).getJquantity());
//			}
//			
//			HSSFRow row111 = sheet.createRow((short)(7+itemlist.size()));//建立新行			
//			HSSFCell cell28 = row111.createCell((short)0);
//			cell28.setCellValue("");
//			cell28.setCellStyle(style2);				
//			HSSFCell cell29 = row111.createCell((short)1);
//			cell29.setCellValue("第一联:仓库");
//			cell29.setCellStyle(style2);			
//			HSSFCell cell30 = row111.createCell((short)2);
//			cell30.setCellValue("第二联:财务   第三联:采购");
//			cell30.setCellStyle(style2);		
//			HSSFCell cell31 = row111.createCell((short)3);
//			cell31.setCellValue("第四联：品管");
//			cell31.setCellStyle(style2);					
//			HSSFCell cell32 = row111.createCell((short)4);
//			cell32.setCellValue("");
//			cell32.setCellStyle(style2);		
//			HSSFCell cell33 = row111.createCell((short)5);
//			cell33.setCellValue("");
//			cell33.setCellStyle(style2);		
//			HSSFCell cell34 = row111.createCell((short)6);
//			cell34.setCellValue("");
//			cell34.setCellStyle(style2);	
//			HSSFCell cell35 = row111.createCell((short)7);
//			cell35.setCellValue("");
//			cell35.setCellStyle(style2);	
//			HSSFCell cell36 = row111.createCell((short)8);
//			cell36.setCellValue("保存期限:15年");
//			cell36.setCellStyle(style2);	
//			HSSFCell cell37 = row111.createCell((short)9);
//			cell37.setCellValue("");
//			cell37.setCellStyle(style2);	
//			HSSFCell cell38 = row111.createCell((short)10);
//			cell38.setCellValue("");
//			cell38.setCellStyle(style2);
//		}
//		response.setContentType("text/html;charset=UTF-8");
//		response.reset();
//		response.setContentType("application/ms-excel");
//		String fileNameDisplay = "采购入库单"+ pw.getPowarecode();
//		try {
//			fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"),
//					"iso-8859-1");
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//		}
//		fileNameDisplay = fileNameDisplay.replace(" ", "%20");
//		response.addHeader("Content-Disposition", "attachment;filename="
//				+ fileNameDisplay + ".xls");
//		
//		OutputStream fout = null;
//		try {
//			fout = response.getOutputStream();
//			wb.write(response.getOutputStream());
//			fout.flush();
//			fout.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
	
	/*@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{

		try {
			String id = request.getParameter("id");
			LogicPoWareDO pw=new LogicPoWareDO();
			List<LogicPoWareItemDO> lp=new ArrayList<LogicPoWareItemDO>();
			if(!"".equals(id)&&id!=null){
				pw =logicPoWareService.findListById(id);
			}
			if(pw.getId()!=null){
				SearchConditions scs = new SearchConditions();
				scs.addCondition("powareid", pw.getId(),SearchCondition.OP_EQUAL);
				scs.setLimitPage(false);
				scs.setRemovedProperty(null);
				lp =logicPoWareService.findItemListByExample(scs).getResults();
			}
//			List<Map<String,Object>> dateMapRows = this.getMapDateRows(purOrderItemDAO.getByPOId(id));
//			Map<String,Object> map = this.getMapDate(purOrder);
			if(lp.size()>0){
				request.setAttribute("pw", pw);
				request.setAttribute("lp", lp);
				request.setAttribute("time", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
				
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename=" + pw.getPowarecode() + ".xls");
			
				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/PoWarePrint.jsp");
			
				dispatcher.forward(request, response);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}	*/
	
//	@RequestMapping(value = "/updateState")
//	public void updateState(HttpServletRequest request,HttpServletResponse response)throws Exception{
//		String id = request.getParameter("rows");
//		Map<String,String> map =new HashMap<String, String>();
//		try{
//		LogicPoWareDO poware = logicPoWareService.findListById(id);
//		poware.setBillstatus((short)0);
//		logicPoWareService.update(poware,  SessionUtil.getUser(request));
//		map.put("msg", "SUCCESS");
//		}catch(Exception e){
//			e.printStackTrace();
//			map.put("msg", "ERROR");
//		}
//		AjaxUtil.printJSonArr(response, JSONObject.fromObject(map).toString());
//	}
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		try {
				String id = request.getParameter("id");
				LogicPoWareDO pw=new LogicPoWareDO();
				List<LogicPoWareItemDO> itemlist=new ArrayList<LogicPoWareItemDO>();
				List<LogicPoWareItemBatchDO> itemBatchDOs=new ArrayList<LogicPoWareItemBatchDO>();
				if(!"".equals(id)&&id!=null){
					pw =logicPoWareService.findListById(id);
				}
				if(pw.getId()!=null){
					SearchConditions scs = new SearchConditions();
					scs.addCondition("powareid", pw.getId(),SearchCondition.OP_EQUAL);
					scs.setLimitPage(false);
					scs.setRemovedProperty(null);
					scs.setOrderBy("code asc");
					itemlist =logicPoWareService.findItemListByExample(scs).getResults();
					if(itemlist!=null){
						int k = 1;
						for (LogicPoWareItemDO logicPoWareItemDO : itemlist) {
							SearchConditions scs2 = new SearchConditions();
							scs2.addCondition("wareItemId", logicPoWareItemDO.getId(),SearchCondition.OP_EQUAL);
							scs2.setLimitPage(false);
							scs2.setRemovedProperty(null);
							scs2.setOrderBy("code asc");
							List<LogicPoWareItemBatchDO> list = logicPoWareItemBatchService.findListByExample(scs2).getResults();
							if(list!=null){
								for (LogicPoWareItemBatchDO logicPoWareItemBatchDO : list) {
									logicPoWareItemBatchDO.setId(k+"");
									if(logicPoWareItemBatchDO.getName()!=null && logicPoWareItemBatchDO.getSpec()!=null){
										logicPoWareItemBatchDO.setSpec(";"+logicPoWareItemBatchDO.getSpec());
									}else{
										logicPoWareItemBatchDO.setSpec(logicPoWareItemBatchDO.getSpec());
									}
									itemBatchDOs.add(logicPoWareItemBatchDO);
									k++;
								}
							}
							
						}
						for (LogicPoWareItemDO logicPoWareItemDO : itemlist) {
							LogicPoWareItemBatchDO batch = new LogicPoWareItemBatchDO();
							if(!"Y".equals(logicPoWareItemDO.getOpenBatch())){
								batch.setId(k+"");
								batch.setName(logicPoWareItemDO.getName());
								if(logicPoWareItemDO.getName()!=null && logicPoWareItemDO.getSpec()!=null){
									batch.setSpec(";"+logicPoWareItemDO.getSpec());
								}else{
									batch.setSpec(logicPoWareItemDO.getSpec());
								}
								batch.setCode(logicPoWareItemDO.getCode());
								batch.setSpec(logicPoWareItemDO.getSpec());
								batch.setJunit(logicPoWareItemDO.getJunit());
								batch.setJquantity(logicPoWareItemDO.getJquantity());
								itemBatchDOs.add(batch);
								k++;
							}
						}
					}
				}
				if(itemBatchDOs.size()<11){
					int s = 11-itemBatchDOs.size();
					int n =itemBatchDOs.size();
					for (int i = 0; i < s; i++) {
						LogicPoWareItemBatchDO item = new LogicPoWareItemBatchDO();
						item.setId(n+1+i+"");
						itemBatchDOs.add(item);
					}
				}
				request.setCharacterEncoding("utf-8");
				response.setContentType("application/vnd.ms-excel;charset=utf-8"); 
//				String fileNameDisplay = "采购入库单";
//				try {
//					fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"),
//							"iso-8859-1");
//				} catch (UnsupportedEncodingException e1) {
//					e1.printStackTrace();
//				}
				response.setHeader("Content-disposition", "attachment;filename="+pw.getPowarecode()+".xls");
				OutputStream os= response.getOutputStream(); 
		//		Map<String,Object> pMap = request.getParameterMap();
		//		List<Map> data = new ArrayList<Map>();
				XLSTransformer transformer = new XLSTransformer();
			    StringBuffer file=new StringBuffer(request.getRealPath("/"));;
				file.append("/views/printer/excelTemplate/poware.xls");
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("pw", pw);
				map.put("item", itemBatchDOs);
				Workbook book= transformer.transformXLS(new FileInputStream(file.toString()), map);    						
					book.write(os);				
					os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
